<?php

namespace app\admin\model;

use think\Model;

/**
 * 养生项目模型
 */
class HealthItems extends Model
{
    protected $name = 'health_items';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    
    // 追加属性
    protected $append = [
        'status_text',
        'duration_text'
    ];

    /**
     * 状态获取器
     */
    public function getStatusTextAttr($value, $data)
    {
        $status = [0 => '下架', 1 => '上架'];
        return $status[$data['status']] ?? '';
    }

    /**
     * 时长获取器
     */
    public function getDurationTextAttr($value, $data)
    {
        return $data['duration'] . '分钟';
    }

    /**
     * 关联门店
     */
    public function store()
    {
        return $this->belongsTo(Store::class, 'store_id', 'id');
    }

    /**
     * 关联创建人
     */
    public function admin()
    {
        return $this->belongsTo(Admin::class, 'admin_id', 'id');
    }

    /**
     * 关联推荐治疗师
     */
    public function medicalStaff()
    {
        return $this->belongsTo(MedicalStaff::class, 'medical_staff_id', 'id');
    }

    /**
     * 关联预约记录（多对多）
     */
    public function appointments()
    {
        return $this->belongsToMany(Appointment::class, 'appointment_health_items_relation', 'health_item_id', 'appointment_id')
                    ->withField(['sort_order'])
                    ->order('sort_order');
    }

    /**
     * 根据门店ID获取项目列表
     */
    public static function getStoreItems($storeId, $status = 1)
    {
        return self::where('store_id', $storeId)
                   ->where('status', $status)
                   ->order('id', 'desc')
                   ->select();
    }

    /**
     * 获取项目选项（用于下拉选择）
     */
    public static function getItemOptions($storeId = null, $status = 1)
    {
        $query = self::where('status', $status);
        
        if ($storeId) {
            $query->where('store_id', $storeId);
        }
        
        return $query->field('id,name,duration,description')
                     ->order('id', 'desc')
                     ->select()
                     ->toArray();
    }
}